/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dotexe.webframework.core.datasources;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dotexe.webframework.core.bindings.BindingCollectionSource;

/**
 *
 * @author jovan.tomasevic
 */
public class HierarchyDataSource extends CollectionDataSource {

    private String childrenPropertyName;

    public HierarchyDataSource(){
        super();
    }
    public HierarchyDataSource(String name){
        super(name);
    }

    // !!!! not finished !!!!
    @Override
    public void bind(ArrayList<String> propertiesToBind)
       throws ClassNotFoundException,NoSuchFieldException, IllegalAccessException, JSONException, SecurityException, NoSuchMethodException, InvocationTargetException{
            BindingCollectionSource binding = new BindingCollectionSource();
            binding.setName(this.getName());
            Integer size = size();

            JSONArray tree = new JSONArray();
            for(int i = 0;i<size;i++){
                // get object from collection with index i
                Object obj = this.get(i);
                Class cls = obj.getClass();
                JSONObject jsonobj = new JSONObject();
                for(int j = 0;j<propertiesToBind.size();j++){
                    Method m = cls.getMethod(String.format("get%s",propertiesToBind.get(j)));
                    Object fValue =  m.invoke(obj);
                    if(fValue == null){
                        fValue = JSONObject.NULL;
                    }
                    jsonobj.put(propertiesToBind.get(j), fValue);
                }
//                Object collection = cls.getMethod(String.format("get%s", this.getChildrenPropertyName())).invoke(obj);
                jsonobj.put(this.getChildrenPropertyName(), new JSONArray());
                jsonobj.put("ruid", i);

                tree.put(jsonobj);

            }
            binding.setSource(tree);
            this.BindingSource = binding;
     }

    /**
     * @return the childrenPropertyName
     */
    public String getChildrenPropertyName() {
        return childrenPropertyName;
    }

    /**
     * @param childrenPropertyName the childrenPropertyName to set
     */
    public void setChildrenPropertyName(String childrenPropertyName) {
        this.childrenPropertyName = childrenPropertyName;
    }
}
